package tk.kikt

import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import tk.kikt.inter.ChannelBean
import tk.kikt.inter.IChannel
import java.net.SocketAddress

class MappingHandler : SimpleChannelInboundHandler<String>() {

    override fun channelRead0(ctx: ChannelHandlerContext, msg: String) {
        //msg为接受到的信息
        val name = ctx.name()

        // 收到消息直接打印输出
        println(ctx.channel().remoteAddress().toString() + " Say : " + msg)

        // 返回客户端消息 - 我已经接收到了你的消息
        ctx.writeAndFlush("your name =$name, Received your message :$msg\n")

        val mapping = MappingHandler.getMapping()
        println("size = ${mapping.size}")
        mapping.forEach { _, channel ->
            channel.getChannel().writeAndFlush("rec message $msg")
        }
    }

    override fun channelActive(ctx: ChannelHandlerContext) {
        super.channelActive(ctx)
        val remoteAddress = ctx.channel().remoteAddress()
        println("$remoteAddress is active")
        val channel = ctx.channel()
        val bean: ChannelBean = ChannelBean()
        bean.setChannel(channel)
        map[remoteAddress] = bean
    }

    override fun channelInactive(ctx: ChannelHandlerContext) {
        super.channelInactive(ctx)
        val remoteAddress = ctx.channel().remoteAddress()
        println("$remoteAddress is inactive")
        map.remove(remoteAddress)
    }

    companion object {
        //key为ip地址和端口  value为一些信息,目前有channel,后续可以保存其他相关信息
        private val map: MutableMap<SocketAddress, IChannel> = HashMap()

        fun getMapping(): Map<SocketAddress, IChannel> {
            return map
        }
    }
}